package com.sunshine.student_register.ui.activity.login;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;

import com.sunshine.student_register.database.StudentRegisterRepository;
import com.sunshine.student_register.database.student.StudentEntity;

/**
 * @author sunshine
 * @date 2020/5/30
 */
public class LoginViewModel extends AndroidViewModel {

    private SharedPreferences sp;
    private StudentRegisterRepository repository;
    private int userId;

    public LoginViewModel(@NonNull Application application) {
        super(application);

        sp = getApplication().getSharedPreferences("app_setting", Context.MODE_PRIVATE);
        repository = new StudentRegisterRepository(getApplication());
    }

    /**
     * 登录方法
     * 判断用户名是否合理
     * 合理则在数据库中查找是否有该用户
     * 并且进行密码比对
     * @return 是否登录成功
     */
    boolean hasLogin(String user, String password){
        try {
            userId = Integer.parseInt(user);
            StudentEntity studentEntity = repository.getStudent(userId);
            return null != studentEntity && studentEntity.getPassword().equals(password);
        }catch (Exception e){
            return false;
        }
    }

    void setLoginUser(){
        sp.edit().putInt("user_id", userId).apply();
    }
}
